/**
 * dataTableList.js Power by YUI-EXT and JSON.
 * 
 * @author 
 * @email 
 */
var DataTableList = { 
	author: "Seraph",
	version: "0.1.0"
};


// -> Column name in Chinese. e.g: CN[1]
var CN = {
	<#list entity.columns as u >
	${u_index}: "${u.name}"<#if u_has_next>,  </#if>        
	</#list>
};

// -> Column name in English
var EN = {
	<#list entity.columns as u >
	${u_index}: "${u.id}"<#if u_has_next>,  </#if>        
	</#list>
};

// -> Cell width
var WD = {
	<#list entity.columns as u >
	${u_index}: "${u.width}"<#if u_has_next>,  </#if>        
	</#list>
};

// -> Data type e.g: float,int,string
var TY = {
	<#list entity.columns as u >
	${u_index}: "${u.dataType}"<#if u_has_next>,  </#if>        
	</#list>
};

<#if javaControllerGenerator.enable>
var URL = {
	queryData : '${entity.name}.do',
	queryList : '${entity.name}ListProvider.do',
	saveOrUpdate : '${entity.name}Save.do?pk=<#list entity.columns as u ><#if u.isPK?exists && u.isPK='true'>${u.id}<#if u_has_next>|</#if></#if></#list>',
	deleteData : '${entity.name}Delete.do'
}
<#else>
var URL = {
	queryData : 'baseRecord.do?bean=${entity.name}',
	queryList : 'baseRecordListProvider.do?bean=${entity.name}',
	saveOrUpdate : 'baseRecordSave.do?bean=${entity.name}&pk=<#list entity.columns as u ><#if u.isPK?exists && u.isPK='true'>${u.id}</#if></#list>',
	deleteData : 'baseRecordDelete.do?bean=${entity.name}'
}
</#if>

var store;
var GridPanel = {

	create : function(){
	
		<#list entity.columns as u >
		<#if u.xtype?exists && u.xtype.name = 'combobox'>
		var ${u.id}DictCombo = new Ext.ux.seraph.DictCombo({url: '${u.xtype.url}', displayField: '${u.xtype.displayField}', valueField: '${u.xtype.valueField}'});
		</#if>
		</#list>

		store = new Ext.data.JsonStore({
			root: 'dataList',
            totalProperty: 'totalCount',
		    url: URL.queryList,
		    fields: [
                <#list entity.columns as u >
                {name: EN[${u_index}], type: TY[${u_index}]}<#if u_has_next>,  </#if>
				</#list>
	        ]
		});
		store.setDefaultSort(EN[1]);
	
    function hrefChange(value, metadata, record){
        return "<div class='div-link' onclick='WinPanel.modify(" + record.get(EN[<#list entity.columns as u ><#if u.isPK?exists && u.isPK='true'>${u_index}</#if></#list>]) + ");'>" + value + "</div>";
    }

	var pagingToolbar = new Ext.ux.PagingToolbar(store);

	var csm = new Ext.grid.CheckboxSelectionModel({});

    var grid = new Ext.grid.GridPanel({
        store: store,
        sm: csm,
        columns: [
            new Ext.grid.RowNumberer(),
        	csm,
            <#list entity.columns as u >
            {header: CN[${u_index}], width: WD[${u_index}], sortable: true, dataIndex: EN[${u_index}]<#if u.isHidden?has_content>, hidden: ${u.isHidden}, hideable: false</#if><#if u.isLink?exists && u.isLink = 'true'>, renderer: hrefChange </#if><#if u.xtype?exists && u.xtype.name = 'combobox'>, renderer: Ext.ux.renderer.Combo(${u.id}DictCombo) </#if>}<#if u_has_next>,  </#if>
			</#list>
        ],
        border: false,
        stripeRows: true,
        width: Ext.get("content").getWidth(),
        height: Ext.get("content").getHeight(),
		tbar: [{
	            text: '新增',
	            iconCls: 'dataTableList-add-icon',
	            handler : function(){
					WinPanel.add();
	            }
            },'-',{
	            text: '删除',
	            iconCls: 'dataTableList-delete-icon',
	            handler : function(){
	            	var ids = '';
	            	var sign = true;
	            	var recordArray = csm.getSelections();
	            	for(var i=0;i < recordArray.length; i++) {
	            		sign = false;
		               	ids += recordArray[i].get('<#list entity.columns as u ><#if u.isPK?exists && u.isPK='true'>${u.id}</#if></#list>') + ',';
	            	}
	            	if(sign) {
	            		 Ext.Msg.alert('提示','请选择要删除记录!');
	            		 return;
	            	}
	            	Ext.Msg.confirm('确认', '确认删除所选记录?&nbsp;', function(val){
	            		if(val == 'yes'){
						 	Ext.Ajax.request({
							   url: URL.deleteData,
							   success: function(req) {
							   		for(var i = 0; i < recordArray.length; i++) {
					            		store.remove(recordArray[i]);
					            	}
					            	//store.load({params:{start:0, limit: pagingToolbar.pageSize}});
							   },
							   failure: Ext.emptyFn,
							   params: { key: ids }
							});
	            		}
	            	})
	            }
        	},'-',' ',
        <#list entity.columns as u >
            <#if u.isQuery?exists && u.isQuery = 'true'>
            <#if u.xtype?exists && u.xtype.name = 'combobox'>
        	{
				text: '${u.name}:'
            },
            {
				xtype: 'selectcombo',
				id: 'query${u.id?cap_first}',
		       	name: EN[${u_index}],
		       	hiddenName: EN[${u_index}],
				fieldLabel: CN[${u_index}],
				width: 90,
                url: '${u.xtype.url}',
                displayField: '${u.xtype.displayField}',
                valueField: '${u.xtype.valueField}'
			},' ',
			<#else>
			{
				text: '${u.name}:'
            },
            {
				xtype:'textfield',
				id: 'query${u.id?cap_first}',
				width: 90
			},' ',
			</#if>
        	</#if>
		</#list>
			{
	            text: '查询',
	            iconCls: 'dataTable-preview-icon',
	            handler : function(){
	        		store.load({params:{start:0, limit: pagingToolbar.pageSize}});
	            }
        	}
        ],
        bbar: pagingToolbar
    });
    grid.render('grid-example');
    store.load({params:{start:0, limit: pagingToolbar.pageSize}});
    
    store.on('beforeload', function(options){
    	var parms = new Array();
	<#list entity.columns as u >
		<#if u.isQuery?exists && u.isQuery = 'true'>
		<#if u.xtype?exists && u.xtype.name = 'combobox'>
		var condition${u_index} = '${u.id}:EXAMPLE_LIKE:' + Ext.getCmp('query${u.id?cap_first}').getValue() + ';'; 
		<#else>
		var condition${u_index} = '${u.id}:EXAMPLE_LIKE:' + $('query${u.id?cap_first}').value + ';';
		</#if>
		parms.push(condition${u_index});
		</#if>
	</#list>
    	Ext.apply(this.baseParams, {condition: parms.join('')});
    });
    
	}
}

var addPanel;
var formPanel;

var WinPanel = {
	
	create : function() {

		formPanel = new Ext.FormPanel({
			baseCls: 'x-plain',
	        labelWidth: 100,
	        frame:true,
	        bodyStyle:'padding-top:10px; padding-left: 10px; border: 0px solid;',
	        autoWidth: true,
			//autoHeight: true,
			autoScroll: true,
	        defaults: {width: 230},
	        defaultType: 'textfield',
			bodyBorder: false,
			border: false,
	        items: [
				<#list entity.columns as u>
				{<#if u.isHidden?exists && u.isHidden = 'true'>	xtype: 'hidden', </#if>
				<#if u.xtype?exists>
					<#if u.xtype.name = 'combobox'>
	            	hiddenName: EN[${u_index}],
	                url: '${u.xtype.url}',
	                displayField: '${u.xtype.displayField}',
	                valueField: '${u.xtype.valueField}',
	                xtype: 'dictcombo',
	            	<#else>
					xtype: '${u.xtype.name}',
	            	</#if>
				</#if>	
					id: EN[${u_index}],
					name: EN[${u_index}],
					fieldLabel:CN[${u_index}],
					allowBlank:${u.allowBlank}
				}<#if u_has_next>,</#if>
				</#list>
	        ]
	    });
	
		addPanel = new Ext.Window({
			el:'panel-example',
	        layout:'fit',
	        title: '新增参数类型',
			width: 350,
	        height: 80 + (20 * ${entity.columns?size}),
			resizable : false,
			items: formPanel,
			closeAction: 'hide',
			buttons: [{
                text:'保存',
                handler: function(){
                	formPanel.form.submit({
                		url: URL.saveOrUpdate,
                		method: 'post',
                		success: function(form, action) {
							addPanel.hide();
							store.reload();
                		},
                		failure: function(form, action) {
							addPanel.hide();
							Ext.Msg.alert('Error', action.result.errors.msg);
                		},
                		clientValidation: true,
                		waitMsg: Message.waitMsg
                	});
				}
            },{
                text: '取消',
                handler: function(){
                   addPanel.hide();
                }
    		}]
		});
	},
	
	add : function() {
		addPanel.setTitle('新增记录');
		addPanel.show();
		formPanel.getForm().reset();
	},
	
	modify : function(key) {
		addPanel.setTitle('修改记录');
		Ext.Ajax.request({
		   url: URL.queryData,
		   success: function(response) {
		   		var data = response.responseText.evalJSON();
				addPanel.show();
				formPanel.getForm().setValues(data);
		   },
		   failure: Ext.emptyFn,
		   params: { id: key }
		});
	}	
}

var Panel = {
	show : function() {
		Ext.QuickTips.init();
		GridPanel.create();
		WinPanel.create();
	}
}
